

//购物车渲染等功能 
class Cart {
    constructor() {
        this.init()
        this.box = document.querySelector(".goods-box")
        this.allbox = document.querySelector(".allbox")
        this.total = document.querySelector(".total")
        this.allnum = document.querySelector(".allnum")
        this.kind = document.querySelector(".kind")
        // console.log(this.box);
    }
    init() {
        //请求数据
        this.load()

    }
    load() {
        $.ajax({
            url: "http://localhost:8888/data/list.json",
            success: (res) => {
                this.res = JSON.parse(res);
                this.getData()
            }
        })
    }
    //读数据
    getData() {
        this.proMsg = getCookie("proMsg2") ? JSON.parse(getCookie("proMsg2")) : [];

        this.render()
    }
    //渲染页面
    render() {
        var str = "";
        for (var i = 0; i < this.res.length; i++) {
            for (var j = 0; j < this.proMsg.length; j++) {
                if (this.res[i].id == this.proMsg[j].id) {
                    str += ` <div data-id="${this.res[i].id}" class="goods">
                  <div class="check">
                      <input class="ipt-check" type="checkbox">
                  </div>
                  <div class="main-goods">
                      <div class="goods-top">
                          <span class="del">×</span>
                      </div>
                      <div class="goods-bottom">
                          <a href=""><img
                                  src="${this.res[i].img}"
                                  width="110px" height="110px"">
                          </a>
                          <div class="goods-name">
                              <a>${this.res[i].info1}</a>
                          </div>
                          <div class="goods-price">
                              单价<span data-price="${this.res[i].price}">${this.res[i].price}</span>元
                          </div>
                          <div class="goods-num">
                              <span>数量</span>
                              <div class="jj">
                                  <button class="btn1">-</button>
                                  <input class="ipt-num" type="text" value="${this.proMsg[j].num}">
                                  <button class="btn2">+</button>
                              </div>
                          </div>
                          <div class="goods-state">
                              操作
                          </div>  </div> </div> </div>`
                }
            }
        }
        this.box.innerHTML = str
        this.addEvent()
    }
    addEvent() {
        let that = this
        //删除功能
        this.box.addEventListener("click", function (event) {
            event = event || window.event
            if (event.target.className.indexOf("del") != -1) {
                that.id = event.target.parentNode.parentNode.parentNode.getAttribute("data-id")
                //再次获取本地库完成对比
                that.setData(function (i) {
                    that.proMsg.splice(i, 1)
                })
                //在页面中删除节点
                event.target.parentNode.parentNode.parentNode.remove()
            }
            that.setPrice()
        })
        //修改数量功能
        this.box.addEventListener("click", function (event) {
            event = event || window.event
            if (event.target.className.indexOf("btn1") != -1) {
                that.id = event.target.parentNode.parentNode.parentNode.parentNode.parentNode.getAttribute("data-id");
                if (event.target.nextElementSibling.value == 1) event.target.nextElementSibling.value = 1
                else {
                    event.target.nextElementSibling.value--
                }
                that.value = event.target.nextElementSibling.value
                that.setData(function (i) {
                    that.proMsg[i].num = that.value
                })
            }
            if (event.target.className.indexOf("btn2") != -1) {
                that.id = event.target.parentNode.parentNode.parentNode.parentNode.parentNode.getAttribute("data-id");
                event.target.previousElementSibling.value++
                that.value = event.target.previousElementSibling.value
                that.setData(function (i) {
                    that.proMsg[i].num = that.value
                })
            }
            if (event.target.parentNode.parentNode.parentNode.parentNode.parentNode.firstElementChild.firstElementChild.checked) {

                //每次点击后都重新渲染 总价格
                that.setPrice()
            }
        })
        //复选框功能
        this.box.addEventListener("click", function (event) {

            event = event || window.event
            if (event.target.className.indexOf("ipt-check") != -1) {
                //每次点击时调用价格函数
                that.setPrice()
                let flag = true
                for (let i = 0; i < this.children.length; i++) {
                    if (!this.children[i].firstElementChild.firstElementChild.checked) {
                        flag = false
                    }
                    that.allbox.checked = flag
                }
            }
        })
        //全选功能
        this.allbox.addEventListener("click", function () {
            for (let i = 0; i < that.box.children.length; i++) {
                that.box.children[i].firstElementChild.firstElementChild.checked = this.checked
            }
            //设置价格
            that.setPrice()
        })

    }
    //寻找当前点击的id和cookie相同的id
    setData(cb) {
        // console.log(this.proMsg);
        var i = 0;
        this.proMsg.some((value, key) => {
            i = key;
            return value.id === this.id
        })
        cb(i)
        setCookie("proMsg2", JSON.stringify(this.proMsg))

    }
    // 设置价格函数
    setPrice() {
        let sum = 0
        let allnum = 0
        //放选择到复选框元素得id
        let arr = []
        //放res里面得price数据
        let arr1 = []
        //放cookie里面得num数据
        let arr2 = []
        //先循环找到所有被选中得复选框得商品id 加入数组arr
        for (let i = 0; i < this.box.children.length; i++) {
            if (this.box.children[i].firstElementChild.firstElementChild.checked) {
                arr.push(this.box.children[i].getAttribute("data-id"))
            }

        }
        //双重for循环找到res和arr得id相等得数据（即复选框选中得得商品所有数据）  然后取到价格数据 加入arr1
        for (let i = 0; i < this.res.length; i++) {
            for (let j = 0; j < arr.length; j++) {
                if (this.res[i].id == arr[j]) {
                    arr1.push(this.res[i].price)
                }
            }
        }
        //对this.proMsg数组进行遍历  按id从小到大排序 
        for (var i = 0; i < this.proMsg.length - 1; i++) {
            for (var j = 0; j < this.proMsg.length - i - 1; j++) {
                if (this.proMsg[j].id > this.proMsg[j + 1].id) {
                    var num = this.proMsg[j];
                    this.proMsg[j] = this.proMsg[j + 1]
                    this.proMsg[j + 1] = num;
                }
            }
        }
        console.log(this.proMsg);
        //双重for循环找到proMsg中和arr得id相等得数据   然后取到我们要的num数据  加入arr2
        for (let i = 0; i < this.proMsg.length; i++) {
            for (let j = 0; j < arr.length; j++) {
                if (this.proMsg[i].id == arr[j]) {
                    arr2.push(this.proMsg[i].num)
                }
            }
        }
        //arr1为所有选中商品得价格数组  arr2为所有选中商品得数量数据
        for (let i = 0; i < arr1.length; i++) {
            //总价格 
            sum += arr1[i] * arr2[i]
            //总件数
            allnum += arr2[i] * 1
        }
        //总价格
        this.total.innerHTML = sum
        //总件数
        this.allnum.innerHTML = allnum
        //商品种类
        this.kind.innerHTML = arr2.length
        // //    console.log(this.total);
    }
}
new Cart()

//点击登录以后 刷新页面改变登录注册样式 (重复功能)
class LoginRegistration {
    constructor() {

        let userMsg = sessionStorage.getItem("userMsg") ? JSON.parse(sessionStorage.getItem("userMsg")) : {};
        if (userMsg.state == 1) {
            let str = `<a href="./load.html">${userMsg.username}</a>
                    <span>|</span>
                     <a class="exit" href="javascript::">退出</a>`
            $(".load").html(str)
            $(".exit").click(function () {
                sessionStorage.removeItem("userMsg");
                let str = `<a href="./load.html">登录</a>`
                $(".load").html(str)
            })
        } else {
            let str = `<a href="./load.html">登录</a>`
            $(".load").html(str)
        }
        //判断  只有登录以后才可以点击购物车
        $(".cart").click(function () {
            if (userMsg.state == 1) {
                location.href = "cart.html"
            } else {
                location.href = "load.html"
            }
        })

    }
}
new LoginRegistration()

